import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //登录界面验证信息
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应和请求字符集类型
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //1.获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || username.equals("") || password == null || password.equals("")) {
            resp.setStatus(403);
            resp.getWriter().write("用户名或密码不能为空！");
            return;
        }
        //2.检验密码是否正确(根据用户名，从数据库中获取对应密码)
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(!password.equals(user.getPassword())) {
            //3.密码错误
            resp.setStatus(403);
            resp.getWriter().write("用户名或密码错误！");
            return;
        }
        //3.密码正确创建会话，跳转到博客列表页
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");
    }
    //强制登录（检验是否登录）
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.从请求中获取会话，判断会话是否存在
        HttpSession session = req.getSession(false);
        if(session == null) {
            //会话不存在，未登录,需要返回一个非2开头的状态码
            resp.setStatus(403);
            return;
        }
        //会话存在，还需要判断User是否存在（退出登录会删除user）
        User user = (User) session.getAttribute("user");
        if(user == null) {
            //未登录,需要返回一个非2开头的状态码
            resp.setStatus(403);
            return;
        }
        //这时才是真的已登陆
        resp.setStatus(200);
    }
}
